package cn.hchaojie.camp.day05.oop;

import java.util.Arrays;
import java.util.Comparator;

public class DemoComparator {
	public static void main(String[] args) {
		String[] strings = {"cd", "abc", "efg", "abcd", "gef"};
		
		// 对数组进行排序
		int[] ints = {8, 5, 7, 8, 12, 50, 0};
		Arrays.sort(ints);
		System.out.println(Arrays.toString(ints));
		
		// 字符串排序，默认按照字母序
		Arrays.sort(strings);
		System.out.println(Arrays.toString(strings));
		
		// 需求：按照字符串长度来排序, Comparator：封装了排序规则
		LenghtComparator comparator = new LenghtComparator();
		Arrays.sort(strings, comparator);
		System.out.println(Arrays.toString(strings));
	}
}

// 根据字符串长度进行排序
// <String> 泛型，指定了排序元素的类型
class LenghtComparator implements Comparator<String> {

	// 返回正数：如果left > right
	// 返回0： 表示左右相等
	// 返回-1： 表示left < right
	@Override
	public int compare(String left, String right) {
		int length1 = left.length();
		int length2 = right.length();
		if (length1 > length2) {
			return 1;
		} else if (length1 == length2) {
			return 0;
		} else {
			return -1;
		}
	}	  
}


